package com.summer.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.summer.commonException.XueChengException;
import com.summer.es.dto.SearchPageResultDto;
import com.summer.es.po.CoursePublish;
import com.summer.es.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchPageResultDto<CoursePublish> getCoursePublishList(int pageNo, int pageSize, String keywords) {
        //1. 准备request
        SearchRequest searchRequest = new SearchRequest("course_publish");

        //2. 封装请求体
        if (!StringUtils.isEmpty(keywords)){
            searchRequest.source()
                    .query(QueryBuilders.multiMatchQuery(keywords, "companyName", "name", "tags", "mtName", "stName", "description"))
                    .from(pageNo - 1) //默认为0，所以要-1
                    .size(pageSize);
        }else {
            searchRequest.source()
                    .query(QueryBuilders.matchAllQuery())
                    .from(pageNo - 1)
                    .size(pageSize);
        }
        //3. 发送请求
        SearchResponse searchResponse = null;
        try {
            searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            XueChengException.cast("搜索发布课程失败, 异常信息：" + e.getMessage());
        }

        //4. 逐层解析结果
        List<CoursePublish> coursePublishList = new ArrayList<>();
        SearchHits hits = searchResponse.getHits();
        long count = hits.getTotalHits().value;
        for (SearchHit hit : hits.getHits()) {
            String coursePublishJson = hit.getSourceAsString();
            CoursePublish coursePublish = JSON.parseObject(coursePublishJson, CoursePublish.class);
            coursePublishList.add(coursePublish);
        }

        // 封装dto
        return new SearchPageResultDto<>(coursePublishList,
                count, pageNo, pageSize);
    }

    @Override
    public void insert2es(CoursePublish coursePublish) {
        String coursePublishJson = JSON.toJSONStringWithDateFormat(coursePublish, "yyyy-MM-dd HH:mm:ss");
        log.info("coursePublishJson = {} ", coursePublishJson);

        //1. 准备request
        IndexRequest indexRequest = new IndexRequest("course_publish").id(coursePublish.getId().toString());
        //2. 准备json
        indexRequest.source(coursePublishJson, XContentType.JSON);

        //3. 发送请求
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("异常信息：{}", e.getMessage(), e);
            XueChengException.cast("数据同步到es失败");
        }
    }


}
